package encryption;

import evthandler.EventMessage;
import java.security.*;

/**
 *
 * @author Casper, Dennis, Jackie, Jakob
 * @version 1.00
 */
public class SHA1 {

    private MessageDigest md;
    public static final char[] HEXCHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    private byte[] password;

    /**
     * Instantiates with SHA1 algorithm
     * @param charPass password in a char array
     */
    public SHA1(char[] charPass) {
        try {
            md = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException ex) {
            new EventMessage("Algorithm SHA1 Could Not Be Found", "Could not find the specified algorithm").showException(ex);
        }
        // Converts charPass to a byte[] via a new String
        password = md.digest(new String(charPass).getBytes());
    }

    /**
     * Returns an SHA1 hash String via hexStringFromBytes method
     * @return sha1 hash String
     */
    public String getEncodedPassword() {
        return hexStringFromBytes(md.digest(password));
    }

    /**
     * Converts a byte array to hexadecimal
     * @param byteArray Byte Array to be converted to Hex
     * @return Returns an SHA1 hash String
     */
    private String hexStringFromBytes(byte[] byteArray) {
        String hexStr = "";
        int hex1;
        int hex2 = 0;

        for (int i = 0; i < byteArray.length; i++) {
            hex1 = ((int) byteArray[i] & 0x000000FF) / 16;
            hex2 = ((int) byteArray[i] & 0x000000FF) % 16;
            hexStr = hexStr + HEXCHARS[hex1] + HEXCHARS[hex2];
        }
        return (hexStr);
    }
}
